<?php

namespace app\api\validate;

use app\common\enum\StatusEnum;
use app\common\model\travel\Line;
use app\common\model\user\Cart;
use app\common\validate\BaseValidate;
use think\Db;

class CartValidate extends BaseValidate
{
    protected $rule = [
        'param' => 'require',
        'cart_id' => 'require|checkCart',
        'line_id' => 'require',
        'price_id' => 'require',
        'selected' => 'require|in:0,1',
    ];

    protected $message = [
        'line_id' => '请选择线路',
        'price_id' => '请选择价格',
        'cart_id.require' => '参数错误',
        'param.require' => '参数错误',
        'selected.require' => '参数错误',
        'selected.in' => '参数错误',
    ];

    protected function sceneAdd()
    {
        $this->only(['line_id', 'price_id']);
    }

    protected function sceneDel()
    {
        $this->only(['cart_id']);
    }

    protected function sceneSelected()
    {
        $this->only(['cart_id', 'selected']);
    }

    protected function sceneChange()
    {
        $this->only(['cart_id', 'goods_num']);
    }

    protected function checkCart($value, $rule, $data)
    {

        $cart = Cart::where(['id' => $value])->find();
        if (!$cart) {
            return '购物车不存在';
        }
        return true;
    }


    protected function checkLine($value, $rule, $data)
    {
        $line = Line::alias('l')
            ->field('l.status')
            ->join('line_price p', 'p.line_id = l.id')
            ->where(['l.id' => $value, 'l.status' => StatusEnum::APPROVED,'p.status' => StatusEnum::APPROVED])
            ->find();

        if (!$line || $line['status'] == 0) {
            return '线路已下架';
        }
        return true;
    }

}